package com.colis.quartz.common.base;

import com.colis.quartz.common.enumerate.ErrorCodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

import static com.colis.quartz.common.enumerate.ErrorCodeEnum.FAIL;
import static com.colis.quartz.common.enumerate.ErrorCodeEnum.SUCCESS;

/**
 * 描述：
 *
 * @author wlp
 * @version 1.0.0
 * @date 2021/10/16 22:08
 */
@Data
@ApiModel("统一返回结果数据实体")
public class RestResult<R> implements Serializable {

    @ApiModelProperty("状态码")
    private Integer code;

    @ApiModelProperty("状态信息")
    private String message;

    @ApiModelProperty("响应状态")
    private Boolean success = false;

    @ApiModelProperty("响应时间戳")
    private Long timestamp = System.currentTimeMillis();

    @ApiModelProperty("返回数据结果")
    private R result;

    public RestResult(ErrorCodeEnum errorCodeEnum, boolean success, R result) {
        this.code = errorCodeEnum.getCode();
        this.message = errorCodeEnum.getMessage();
        this.success = success;
        this.result = result;
    }

    public RestResult(ErrorCodeEnum errorCodeEnum, R result) {
        this.code = errorCodeEnum.getCode();
        this.message = errorCodeEnum.getMessage();
        this.result = result;
    }

    public RestResult(Integer code, String message, R result) {
        this.code = code;
        this.message = message;
        this.result = result;
    }

    /**
     * <p> 方法描述: 判断成功OR失败且无结果返回方法 </p>
     *
     * @param flag 判断条件
     * @return RestResult<List < R>>
     * @author wlp
     * @date 2021/10/16 22:25
     */
    public RestResult<List<R>> hasSuccess(Predicate<R> flag) {
        if (flag.test(this.result)) {
            return success();
        }
        return fail();
    }

    /**
     * <p> 方法描述: 成功且有返回数据方法 </p>
     *
     * @param result 返回的数据
     * @return RestResult<R>
     * @author wlp
     * @date 2021/10/16 22:26
     */
    public static <R> RestResult<R> success(R result) {
        return new RestResult<>(SUCCESS, true, result);
    }

    /**
     * <p> 方法描述: 成功且无返回数据方法 </p>
     *
     * @return RestResult<List < R>>
     * @author wlp
     * @date 2021/10/16 22:26
     */
    public static <R> RestResult<List<R>> success() {
        return new RestResult<>(SUCCESS, true, Collections.emptyList());
    }

    /**
     * <p> 方法描述: 失败且无返回数据方法 </p>
     *
     * @return RestResult<List < R>>
     * @author wlp
     * @date 2021/10/16 22:28
     */
    public static <R> RestResult<List<R>> fail() {
        return new RestResult<>(FAIL, false, Collections.emptyList());
    }

    /**
     * <p> 方法描述: 失败且有返回数据方法 </p>
     *
     * @return RestResult<List < R>>
     * @author wlp
     * @date 2021/10/16 22:28
     */
    public static <R> RestResult<R> fail(R result) {
        return new RestResult<>(FAIL, false, result);
    }


}
